package cn.fjy.android.phone.listener;

import android.os.Vibrator;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import cn.fjy.android.phone.worker.TalkTimeRemind;
import cn.fjy.android.res.Constant;
import cn.fjy.android.utils.APPSession;
/**
 * 电话状态监听
 * 
 * @author GrayF
 * 
 */
public class GRPhoneStateListener extends PhoneStateListener {

	private String tag = "GRPhoneStateListener";
	
	private Vibrator vibrator;
	
	private TalkTimeRemind talkTimeRemind;

	public GRPhoneStateListener(Vibrator vibrator){
		this.vibrator = vibrator;
		talkTimeRemind = new TalkTimeRemind(vibrator);
	}
	
	
	@Override
	public void onCallStateChanged(int state, String incomingNumber) {
		Log.i(tag,"电话状态监听---上一个电话状态："+PrePhoneState);
		checkState(state);
		switch (state) {
		case TelephonyManager.CALL_STATE_IDLE:
			PrePhoneState = TelephonyManager.CALL_STATE_IDLE;
			Log.i(tag, "TelephonyManager.CALL_STATE_IDLE");
			break;
		case TelephonyManager.CALL_STATE_OFFHOOK:
			PrePhoneState = TelephonyManager.CALL_STATE_OFFHOOK;
			Log.i(tag, " TelephonyManager.CALL_STATE_OFFHOOK");
			break;
		case TelephonyManager.CALL_STATE_RINGING:
			PrePhoneState = TelephonyManager.CALL_STATE_RINGING;
			Log.i(tag, "TelephonyManager.CALL_STATE_RINGING");
			break;
		default:
			break;
		}
	}

	private void checkState(int state) {
		// 挂机
		if (PrePhoneState == TelephonyManager.CALL_STATE_OFFHOOK) {
			if (state == TelephonyManager.CALL_STATE_IDLE) {
				Log.i(tag,
						"挂机，checkState##CALL_STATE_OFFHOOK___TO___CALL_STATE_IDLE");
				if(talkTimeRemind.isActive()){
					talkTimeRemind.stopRemind();
				}
				TalkTimeRemind	callOnTalkTimeRemind = (TalkTimeRemind)APPSession.getValue(Constant.SESSION_KEY_TAKLTIMEREMID);
				if(callOnTalkTimeRemind!=null&&callOnTalkTimeRemind.isActive()){
					callOnTalkTimeRemind.stopRemind();
				}
				vibrator.vibrate(100);
			}
		}

		// 来电接通
		if (PrePhoneState == TelephonyManager.CALL_STATE_RINGING) {
			if (state == TelephonyManager.CALL_STATE_OFFHOOK) {
				Log.i(tag,
						"来电接通，checkState##CALL_STATE_RINGING___TO___CALL_STATE_OFFHOOK");
				if (TalkTimeRemind.isEnable&&!talkTimeRemind.isActive()) {
					new Thread(talkTimeRemind).start();
				}
			}
		}
	}

	private static int PrePhoneState = TelephonyManager.CALL_STATE_IDLE;

}
